package cn.alm.allinoneboot.service;

import cn.alm.allinoneboot.common.CommonResult;
import cn.alm.allinoneboot.entity.Brand;
import cn.alm.allinoneboot.mapper.BrandMapper;
import cn.alm.allinoneboot.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class BrandService {

    @Resource
    private BrandMapper brandMapper;

    // 查询全部品牌（不分页）
    public List<Brand> getAllBrandList() {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("update_time");
        return brandMapper.selectList(wrapper);
    }

    // 查询品牌列表分页
    public CommonResult queryBrandListPage(String name, Integer current, Integer size) {
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like("name", name);
        }
        wrapper.orderByDesc("update_time");
        Page<Brand> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        brandMapper.selectPage(page, wrapper);
        CommonResult cr = new CommonResult();
        cr.ok();
        cr.setData(page);
        return cr;
    }

    // 新增品牌
    public CommonResult addBrand(Brand brand) {
        brand.setId(UUID.randomUUID().toString());
        String currentDateWithFormat = DateUtil.getCurrentDateWithFormat();
        brand.setCreateTime(currentDateWithFormat);
        brand.setUpdateTime(currentDateWithFormat);
        int insert = brandMapper.insert(brand);
        CommonResult cr = new CommonResult();
        if (insert > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }

    // 根据品牌id获取品牌信息
    public CommonResult getBrandById(Brand brand) {
        Brand b = brandMapper.selectById(brand.getId());
        CommonResult cr = new CommonResult();
        if (b != null) {
            cr.ok();
            cr.setData(b);
        } else {
            cr.error();
        }
        return cr;
    }

    // 根据品牌id删除品牌
    public CommonResult deleteBrandById(Brand brand) {
        int delete = brandMapper.deleteById(brand.getId());
        CommonResult cr = new CommonResult();
        if (delete > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }

    // 更新品牌
    public CommonResult updateBrand(Brand brand) {
        String currentDateWithFormat = DateUtil.getCurrentDateWithFormat();
        brand.setUpdateTime(currentDateWithFormat);
        int update = brandMapper.updateById(brand);
        CommonResult cr = new CommonResult();
        if (update > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }
}
